package com.lw.smartdevice.websocket.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.lw.smartdevice.pojo.SysHumiture;
import com.lw.smartdevice.service.SysHumitureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * @author Administrator
 * @version 1.0
 * @description:
 * @date 2022/3/24 22:15
 *
 * 对设备进行电源控制的websocket,主要是给继电器设备进行命令发送的
 */
@Component
public class HumitureCommandHandler extends BaseCommandHandler {

    private ObjectMapper objectMapper;

    @Autowired
    public void setObjectMapper(ObjectMapper objectMapper) {
        this.objectMapper = objectMapper;
    }

    private SysHumitureService sysHumitureService;

    @Autowired
    public void setSysHumitureService(SysHumitureService sysHumitureService) {
        this.sysHumitureService = sysHumitureService;
    }

    //收到数据单独处理


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        CompletableFuture.runAsync(()->{
            try {
                super.handleTextMessage(session, message);
                System.err.println("单独处理温湿度数据");
                String deviceKey = (String) session.getAttributes().get("deviceKey");//设备id
                String payload = message.getPayload();//数据，是一个json格式的数据
                Map map = objectMapper.readValue(payload, Map.class);//包含humidity,temperature两个key
                SysHumiture sysHumiture=new SysHumiture();
                sysHumiture.setDeviceId(deviceKey);
                sysHumiture.setUploadTime(new Date());
                sysHumiture.setHumidity((Double) map.get("humidity"));
                double temperature = (double) map.get("temperature");
                double sheshi=(temperature-32)/1.8;//转成摄氏温度
                sysHumiture.setTemperature(sheshi);
                sysHumitureService.addSysHumiture(sysHumiture);
            } catch (Exception e) {
                e.printStackTrace();
            }
        });

    }
}
